package dao;

import pojo.User;
import utils.DbUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl extends DbUtils implements UserDao{
    @Override
    public User selectByUsername(String username) throws SQLException {
        List<String> list = new ArrayList<>();
        list.add(username);
        String sql = "select * from user where username = ?";
        ResultSet resultSet = query(sql, list);
        User user = new User();
        while (resultSet.next()){
            user.setUsername(resultSet.getString("username"));
            user.setPassword(resultSet.getString("password"));
        }
        closeAll();
        return user;
    }

    @Override
    public int addUser(User user) {
        String sql = "insert into user(username,password) values(?,?) ";
        List list = new ArrayList();
        list.add(user.getUsername());
        list.add(user.getPassword());
        closeAll();
        return update(sql, list);
    }

    @Override
    public List<User> selectAll() throws SQLException {
        String sql = "select * from user";
        List list = new ArrayList();
        List<User> users = new ArrayList<>();
        ResultSet query = query(sql, list);
        while (query.next()){
            User user = new User();
            user.setUsername(query.getString("username"));
            user.setPassword(query.getString("password"));
            users.add(user);
        }
        return users;
    }
}
